package com.jblv.frame.user.service.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.Properties;

/**
 * 数据库启动类
 * 
 * @author tjianqun@linewell.com
 *
 * @date 2017年7月27日 下午7:30:16
 */
@Configuration
@EnableTransactionManagement
public class DataBaseConfiguration implements EnvironmentAware {
	
	private static final Logger logger = LoggerFactory.getLogger(DataBaseConfiguration.class);

    private Environment environment;

    private static Properties propertyResolver;


    @Override
	public void setEnvironment(Environment env) {

        this.environment = env;
        Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment);
        Binder binder = new Binder(sources);
        BindResult<Properties> bindResult = binder.bind("jdbc", Properties.class);
        propertyResolver = bindResult.get();
	}

	@Bean
	public PlatformTransactionManager txManager(DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(initMethod = "init", destroyMethod = "close")
	public DruidDataSource datasource() {
		if (StringUtils.isEmpty(propertyResolver.getProperty("url"))) {
            System.out.println("Your database connectio n pool configuration is incorrect!"
                    + " Please check your Spring profile, current profiles are:"
                    + Arrays.toString(environment.getActiveProfiles()));
            throw new ApplicationContextException(
                    "Database connection pool is not configured correctly");
		}
		DruidDataSource datasource = new DruidDataSource();
		datasource.setUrl(propertyResolver.getProperty("url"));
		datasource.setDriverClassName(propertyResolver.getProperty("driverName"));
		datasource.setUsername(propertyResolver.getProperty("userName"));
		datasource.setPassword(propertyResolver.getProperty("password"));
		datasource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize")));
		datasource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle")));
		datasource.setMaxWait(Long.parseLong(propertyResolver.getProperty("maxWait")));
		datasource.setTimeBetweenEvictionRunsMillis(
				Long.parseLong(propertyResolver.getProperty("timeBetweenEvictionRunsMillis")));
		datasource.setMinEvictableIdleTimeMillis(
				Long.parseLong(propertyResolver.getProperty("minEvictableIdleTimeMillis")));
		logger.info("DuridConfig数据源完成");
		return datasource;
	}
}
